/**
 * 企业成员查询表单组件
 */

'use client';

import React from 'react';
import {
  Form,
  Input,
  Select,
  Button,
  Space,
  Card,
  Row,
  Col,
  Tag,
} from 'antd';
import {
  SearchOutlined,
  ClearOutlined,
  UserOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import type { MemberQueryParams } from '../types/member';
import { useMemberMeta } from '../hooks/useMembers';

const { Option } = Select;

interface MemberQueryFormProps {
  onSearch: (params: MemberQueryParams) => void;
  loading?: boolean;
  initialValues?: MemberQueryParams;
}

export default function MemberQueryForm({
  onSearch,
  loading = false,
  initialValues,
}: MemberQueryFormProps) {
  const [form] = Form.useForm();
  const { departments, roles } = useMemberMeta();

  const handleSearch = () => {
    const values = form.getFieldsValue();
    
    // 处理查询参数
    const params: MemberQueryParams = { ...values };
    
    // 移除空值
    Object.keys(params).forEach(key => {
      const value = params[key as keyof MemberQueryParams];
      if (value === undefined || value === null || value === '') {
        delete params[key as keyof MemberQueryParams];
      }
    });

    // 确保重置到第一页（API使用0作为第一页）
    params.page_index = 0;

    onSearch(params);
  };

  const handleReset = () => {
    form.resetFields();
    // 重置时也要确保从第一页开始，并使用默认页面大小
    onSearch({ page_index: 0, page_size: 30 });
  };

  const getStatusTag = (status: string) => {
    const statusMap: Record<string, { color: string; text: string }> = {
      active: { color: 'green', text: '激活' },
      inactive: { color: 'red', text: '未激活' },
      pending: { color: 'orange', text: '待激活' },
    };
    const config = statusMap[status] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  return (
    <Card 
      title={
        <Space>
          <TeamOutlined style={{ color: '#1890ff' }} />
          <span>成员查询条件</span>
        </Space>
      }
      size="small"
      styles={{ body: { paddingBottom: 8 } }}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={initialValues}
        onFinish={handleSearch}
      >
        <Row gutter={[12, 8]}>
          {/* 第一行：基本查询条件 */}
          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="用户名" name="name" style={{ marginBottom: 8 }}>
              <Input 
                placeholder="搜索用户名" 
                allowClear 
                size="small"
                prefix={<UserOutlined style={{ color: '#bfbfbf' }} />}
              />
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="显示名称" name="display_name" style={{ marginBottom: 8 }}>
              <Input 
                placeholder="搜索显示名称" 
                allowClear 
                size="small"
              />
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="邮箱" name="email" style={{ marginBottom: 8 }}>
              <Input 
                placeholder="搜索邮箱" 
                allowClear 
                size="small"
                type="email"
              />
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="状态" name="status" style={{ marginBottom: 8 }}>
              <Select placeholder="选择状态" allowClear size="small">
                <Option value="active">
                  {getStatusTag('active')} 激活
                </Option>
                <Option value="inactive">
                  {getStatusTag('inactive')} 未激活
                </Option>
                <Option value="pending">
                  {getStatusTag('pending')} 待激活
                </Option>
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="角色" name="role" style={{ marginBottom: 8 }}>
              <Select
                placeholder="选择角色"
                allowClear
                showSearch
                size="small"
                optionFilterProp="children"
                filterOption={(input, option) =>
                  String(option?.label || option?.children || '').toLowerCase().includes(input.toLowerCase())
                }
              >
                {roles.map(role => (
                  <Option key={role} value={role}>
                    {role}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="部门" name="department" style={{ marginBottom: 8 }}>
              <Select
                placeholder="选择部门"
                allowClear
                showSearch
                size="small"
                optionFilterProp="children"
                filterOption={(input, option) =>
                  String(option?.label || option?.children || '').toLowerCase().includes(input.toLowerCase())
                }
              >
                {departments.map(dept => (
                  <Option key={dept} value={dept}>
                    {dept}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={[12, 8]}>
          {/* 第二行：高级筛选条件 */}
          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="管理员" name="is_admin" style={{ marginBottom: 8 }}>
              <Select placeholder="是否管理员" allowClear size="small">
                <Option value={true}>
                  <Tag color="red">是</Tag> 管理员
                </Option>
                <Option value={false}>
                  <Tag color="default">否</Tag> 普通成员
                </Option>
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="排序方式" name="sort_by" style={{ marginBottom: 8 }}>
              <Select placeholder="选择排序字段" allowClear size="small">
                <Option value="created_at">创建时间</Option>
                <Option value="last_login_at">最后登录</Option>
                <Option value="name">用户名</Option>
                <Option value="display_name">显示名称</Option>
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="排序方向" name="sort_order" style={{ marginBottom: 8 }}>
              <Select placeholder="排序方向" allowClear size="small">
                <Option value="desc">降序</Option>
                <Option value="asc">升序</Option>
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={3}>
            <Form.Item label="每页显示" name="page_size" initialValue={30} style={{ marginBottom: 8 }}>
              <Select placeholder="每页数量" size="small">
                <Option value={10}>10条</Option>
                <Option value={20}>20条</Option>
                <Option value={30}>30条</Option>
                <Option value={50}>50条</Option>
                <Option value={100}>100条</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row style={{ marginTop: 8 }}>
          <Col span={24}>
            <Space>
              <Button
                type="primary"
                icon={<SearchOutlined />}
                onClick={handleSearch}
                loading={loading}
                size="small"
              >
                查询
              </Button>
              <Button
                icon={<ClearOutlined />}
                onClick={handleReset}
                size="small"
              >
                重置
              </Button>
            </Space>
          </Col>
        </Row>
      </Form>
    </Card>
  );
}